import {renderAsyncRouter} from '@/router/generator-routers.js'

export default {
    state: {
        menuList: [],
        permList: [],
        routes: [],
        editableTabsValue: 'Index',
        editableTabs: [{
          title: '首页',
          name: 'Index',
        }]
    },
    mutations: {
        setMenuList(state, menus) {
            state.menuList = menus
        },
        setPermList(state, perms) {
            state.permList = perms
        },
        setRoutes(state, routes) {
            state.routes = routes
        },
        // 添加标签
        addTab(state, tab) {
            // 查询标签是否已经存在
            let index = state.editableTabs.findIndex(e => e.name === tab.name)
            // 如果不存在，则添加
            if(index === -1) {
                state.editableTabs.push({
                    title: tab.title,
                    name: tab.name,
                });
            }
            state.editableTabsValue = tab.name
        },
        // 退出时清空状态
        resetState(state) {
            state.menuList = []
            state.permList = []
            state.routes = []
            state.editableTabs = [{
                title: '首页',
                name: 'Index',
            }],
            state.editableTabsValue = 'Index'
            // 清除token
            sessionStorage.removeItem('token')
        }
    },
    actions: {
        GenerateRoutes({ commit }, menuList) {
            return new Promise((reslove, reject) => {
                renderAsyncRouter(menuList).then(res => {
                    commit('setRoutes', res)
                    commit('setMenuList', menuList)
                    reslove(res)
                })
            })
        }
    },
    getters: {
    }
}